let type = process.env.VUE_APP_API_ENV ==='dev'? 'dev':'production'
let url = {
    dev: 'https://zhuanti.qa.chebada.com/activityapi/Handler/',
    production: 'https://zhuanti.chebada.com/activityapi/Handler/',
    t: 'https://zhuanti.t.chebada.com/activityapi/Handler/',
    local: ''
}
let isCBD = navigator.userAgent.indexOf("chebada") != -1;

/**
 * 公用ajax组件
 * param为请求参数body,没有则传{};
 * handler接口名;
 * serviceName服务名;
 * Created by wusk on 19/12/13.
 */
function sendRequest(param, handler, serviceName) {
    let postUrl = url[type] + handler
    return new Promise((resolve, reject) => {
        $.ajax({
            dataType: 'json',
            url: postUrl,
            type: 'post',
            timeout: '8000',
            data: JSON.stringify({
                header: {
                    "serviceName": serviceName
                },
                body: param
            }),
            beforeSend: function () {
                cbdztUtil.Toast.showLoading()
            },
            success: function (res) {
                cbdztUtil.Toast.hideLoading()
                resolve(res)
            },
            error: function (error) {
                cbdztUtil.Toast.hideLoading()
                reject(error)
            }
        })
    })
}

function isIOS() {
    if (isCBD) {
        bridge.userInfoPlugins.getSystemInfo().then(res => {
            var ios = res.clientInfo.osType;
            if (ios === "ios") {
                return true
            }
        });
    }
    return false
}

const getQuery = () => {
  let hash = location.hash;
  let search = location.search;
  return {...getParam(search), ...getParam(hash)}
  function getParam(str){
    let result = {};
    let paramStringMatch = str.match(/\?(.*)/) || [];
    let paramString = paramStringMatch[1] || '';
    let andSplit = paramString.split('&');
    andSplit.forEach(item => {
      let equalSplit = item.split('=');
      if(equalSplit[0])result[equalSplit[0]] = decodeURIComponent(equalSplit[1])
    });
    return result;
  }
}

const getUrlParam = (name) => {
  let query = getQuery() || {};
  return query[name];
}

let env = '';
const getEnv = async () => {
  return new Promise((resolve, reject) => {
    if (env) return resolve(env);
    const isCBD = navigator.userAgent.indexOf('chebada') != -1;
    const isWX =
      navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1;
    if (isCBD) resolve('cbd');
    else if (!isWX) resolve('h5');
    else {
      try {
        wx.miniProgram.getEnv((res) => {
          if (res.miniprogram) {
            resolve('mini');
          } else {
            resolve('wx');
          }
        });
      } catch (err) {
        resolve('wx');
      }
    }
  }).then((res) => {
    if (!env) env = res;
    return res;
  });
};

// 活动结束(app, mini, h5)
const activityEnd = async () => {
  const env = await getEnv();

  if (env === "cbd") {
    // bridge.naviPlugins.openWebPage({
    //   webPageUrl: "https://zhuanti.chebada.com/act/app/2020/11/activitiesend/"
    // });
    document.location.replace(
      "https://zhuanti.chebada.com/act/app/2020/11/activitiesend/"
    );
  } else if (env === "mini") {
    wx.miniProgram.redirectTo({
      url: "/pages/common/activities-end/activities-end"
    });
  } else {
    window.location.href =
      "https://zhuanti.chebada.com/act/app/2020/11/activitiesend/";
  }
};


// 在不同环境内跳转到不同的页面-跳转组件
const jumpPage = async param => {
  const env = await getEnv();
  const {url, appUrl, miniUrl, h5Url, downloadUrl} = param;
  
  let envcbdUrl = getUrlEnv(appUrl || url);
  let envminiUrl = getUrlEnv(miniUrl || url);
  let envh5Url = getUrlEnv(h5Url || url);
  let goAppUrl = appUrl || url;
  let goMiniUrl = miniUrl || url;
  let goh5Url = h5Url || url;

  if (env === "cbd") {

    if (goAppUrl) {
      if (envcbdUrl == "miniurl") {
        try {
          bridge.utilsPlugins.openMiniProgram({
            path: goAppUrl,
            userName: "gh_0aacaec14151"
          });
          return;
        } catch (e) { 
          console.log(e);
        }
      } else bridge.naviPlugins.openWebPage({ webPageUrl: goAppUrl });
    }

  } else if (env === "mini") {

    if (goMiniUrl) {
      if (envminiUrl == "miniurl") {
        wx.miniProgram.navigateTo({ url: goMiniUrl });
      } else window.location.href = goMiniUrl;
    }

  } else {
    if (goh5Url) window.location.href = envh5Url=="https" ? goh5Url : downloadUrl;
  }
};

const getUrlEnv = url => {
  if (url.substr(0,6) == "/pages") {
    return "miniurl"
  } else if(url.indexOf("https://") == 0) {
    return "https"
  } else if(url.indexOf("cbdbusbutler://") == 0){
    return "cbdurl"
  } else return "url"
}

// 小程序跳转网页
const toWxWeb = url => {
  wx.miniProgram.navigateTo({ url });
};

export {
  sendRequest,
  getUrlParam,
  getQuery,
  isIOS, 
  getEnv,
  activityEnd,
  toWxWeb,
  jumpPage
}